package user

import (
	"enjoy_wangyashuo/base"
	"enjoy_wangyashuo/formdata"
	"enjoy_wangyashuo/internal/model/redis"
	"enjoy_wangyashuo/internal/server"
	"enjoy_wangyashuo/pkg"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

func Login(c *gin.Context) {
	var data formdata.UserLogin
	if err := c.ShouldBindJSON(&data); err != nil {
		base.RespData(c, "", err)
		return
	}
	token, err := server.Login(data)
	if err != nil {
		base.RespData(c, "", err)
		return
	}
	base.RespData(c, token, err)
	fmt.Println("登录成功", token)
}
func Register(c *gin.Context) {
	var data formdata.UserRegister
	if err := c.ShouldBindJSON(&data); err != nil {
		base.RespData(c, "手机号格式错误", errors.New("手机号格式错误"))
		return
	}
	token, err := server.Register(data)
	base.RespData(c, token, err)
}
func SendCode(c *gin.Context) {
	var data formdata.SendCode
	if err := c.ShouldBindJSON(&data); err != nil {
		base.RespData(c, nil, err)
		return
	}
	if !pkg.ValidatePhoneNumber(data.Phone) {
		base.RespData(c, "", errors.New("手机号格式效验错误"))
		return
	}
	code := pkg.NumCodeString()
	err := pkg.SendSmsCode(data.Phone, code)
	if err != nil {
		fmt.Println("短信错误消息》》", err)
		return
	}
	key := "phone_:" + data.Phone + "_type" + data.CodeType
	err = redis.SetRedisVal(key, code, time.Minute*30)
	base.RespData(c, code, nil)
	fmt.Println("发送成功", code)
}

// 用户修改密码
func UpdatePasswordByUserId(c *gin.Context) {
	var data formdata.UpdateDara
	if err := c.ShouldBindJSON(&data); err != nil {
		base.RespData(c, nil, err)
		return
	}
	userId := pkg.GetAutoUserID(c)
	fmt.Println("111111", userId)
	err := server.UpdatePasswordByUserId(data, userId)
	if err != nil {
		base.RespData(c, nil, err)
		return
	}
	base.RespData(c, "", err)
}
